﻿using System;
using System.Windows.Forms;
using System.Data;
using System.Threading;
using System.IO;

namespace ExamServer.Forms
{
    public partial class FormServer : Form
    {
        private StreamWriter fileStream = null;

        public FormServer()
        {
            ListenConnection.ShowText += new ShowTextCallback(On_ShowText);
            Client.ShowText += new ShowTextCallback(On_ShowText);
            ListenConnection.Bind += new BindCallback(On_Bind);
            Client.Bind += new BindCallback(On_Bind);
            Client.WriteLog += new WriteLogCallback(On_WriteLog);
            InitializeComponent();
        }

        private void FormServer_Load(object sender, EventArgs e)
        {
            toolStripButton2.Enabled = false;
            ToolStripMenuItem_StopService.Enabled = false;
            ListenConnection.DataTable_Load();
            dataGridView1.DataSource = ListenConnection.dt;
            if (!Directory.Exists(Directory.GetCurrentDirectory() + "\\Log"))
            {
                Directory.CreateDirectory(Directory.GetCurrentDirectory() + "\\Log");
            }
            DateTime t = DateTime.Now;
            string logPath = Directory.GetCurrentDirectory() + "\\Log\\" + "ServerLog " + t.Year + "-" + t.Month + "-" + t.Day + " " + t.Hour + "-" + t.Minute + "-" + t.Second + ".log";
            fileStream = new StreamWriter(logPath, true);
            fileStream.AutoFlush = true;
        }

        private void On_Bind()
        {
            try
            {
                if (this.dataGridView1.InvokeRequired)
                {
                    BindCallback d = new BindCallback(On_Bind);
                    this.Invoke(d);
                }
                else
                {
                    label1.Text = "当前连接数 " + ListenConnection.clients.Count;
                    ListenConnection.dt.Clear();
                    for (int i = 0; i < ListenConnection.clients.Count; i++)
                    {
                        DataRow dr = ListenConnection.dt.NewRow();
                        dr["Address"] = ListenConnection.clients[i].WorkSock.RemoteEndPoint;
                        dr["AdminName"] = ListenConnection.clients[i].UserName;
                        ListenConnection.dt.Rows.Add(dr);
                    }
                    dataGridView1.DataSource = null;
                    dataGridView1.DataSource = ListenConnection.dt;
                    dataGridView1.Columns[0].Width = 120;
                    dataGridView1.Columns[1].Width = 80;
                }
            }
            catch(Exception)
          {
              
            }
        }

        private void On_ShowText(string text)
        {
            try
            {
                if (this.textBox1.InvokeRequired)
                {
                    ShowTextCallback d = new ShowTextCallback(On_ShowText);
                    this.Invoke(d, new object[] { text });
                }
                else
                {
                    if (textBox1.Text.Length >= 5000) textBox1.Text = String.Empty;
                    textBox1.AppendText(text);
                    textBox1.ScrollToCaret();

                }
            }
            catch (Exception)
            {
            }
        }

        private void On_WriteLog(int id, string name, string remoteEndPoint, string detail)
        {
            try
            {
                if (this.textBox1.InvokeRequired)
                {
                    WriteLogCallback d = new WriteLogCallback(On_WriteLog);
                    this.Invoke(d, new object[] { id, name, remoteEndPoint, detail });
                }
                else
                {
                    fileStream.WriteLine("[" + DateTime.Now + "] [" + id + "] [" + name + "] [" + remoteEndPoint + "] " + detail);
                }
            }
            catch(Exception)
            {
                
            }
        }

        private void notifyIcon_OnClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                if (this.WindowState == FormWindowState.Normal)
                {
                    this.Hide();
                    this.WindowState = FormWindowState.Minimized;
                }
                else if (this.WindowState == FormWindowState.Minimized)
                {
                    this.Show();
                    this.WindowState = FormWindowState.Normal; //还原窗体 
                }
            }
        }

        private void Form_SizeChanged(object sender, EventArgs e)
        {
            if (this.WindowState == FormWindowState.Normal)
            {
                this.ShowInTaskbar = true;

            }
            else if (this.WindowState == FormWindowState.Minimized)
            {
                this.ShowInTaskbar = false;
            }
            dataGridView1.Height = this.Height - 107;
            textBox1.Width = this.Width - 230;
            textBox1.Height = this.Height - 72;
        }

        private void OnSetting_Click(object sender, EventArgs e)
        {
            DialogSetting setDlg = new DialogSetting();
            setDlg.ShowDialog(this);
        }

        private void OnExit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void ToolStripMenuItemClose_Click(object sender, EventArgs e)
        {
            string id = dataGridView1.SelectedRows[0].Cells["AdminName"].Value.ToString();
            ListenConnection.OutLineByUserName(id);
        }

        private void dataGridView1_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                if (e.RowIndex >= 0)
                {
                    //若行已是选中状态就不再进行设置
                    if (dataGridView1.Rows[e.RowIndex].Selected == false)
                    {
                        dataGridView1.ClearSelection();
                        dataGridView1.Rows[e.RowIndex].Selected = true;
                    }
                    //只选中一行时设置活动单元格
                    if (dataGridView1.SelectedRows.Count == 1)
                    {
                        dataGridView1.CurrentCell = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex];
                    }
                    //弹出操作菜单
                    contextMenuStrip2.Show(MousePosition.X, MousePosition.Y);
                }
            }
        }

        private void ToolStripMenuItem_Release_Click(object sender, EventArgs e)
        {
            DialogRelease rDlg = new DialogRelease();
            rDlg.ShowDialog();
        }

        private void toolStripButton4_Click(object sender, EventArgs e)
        {
            OnSetting_Click(sender, e);
        }

        private void toolStripButton3_Click(object sender, EventArgs e)
        {
            ToolStripMenuItem_Release_Click(sender, e);
        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            toolStripButton1.Enabled = false;
            ToolStripMenuItem_BeginService.Enabled = false;
            toolStripButton2.Enabled = true;
            ToolStripMenuItem_StopService.Enabled = true;
            ListenConnection.listenThread = new Thread(new ThreadStart(ListenConnection.Listen));
            ListenConnection.listenThread.Start();
        }

        private void toolStripButton2_Click(object sender, EventArgs e)
        {
            toolStripButton2.Enabled = false;
            ToolStripMenuItem_StopService.Enabled = false;
            toolStripButton1.Enabled = true;
            ToolStripMenuItem_BeginService.Enabled = true;
            ListenConnection.Close();
            On_ShowText("停止服务！\r\n");
        }

        private void ToolStripMenuItem_BeginService_Click(object sender, EventArgs e)
        {
            toolStripButton1_Click(sender, e);
        }

        private void ToolStripMenuItem_StopService_Click(object sender, EventArgs e)
        {
            toolStripButton2_Click(sender, e);
        }

        private void toolStripButton5_Click(object sender, EventArgs e)
        {
            DialogBackUp bDlg = new DialogBackUp();
            bDlg.ShowDialog();
        }

        private void ToolStripMenuItem_BackUp_Click(object sender, EventArgs e)
        {
            toolStripButton5_Click(sender, e);
        }
    }
}
